package com.hd123.rumba.qt.collate;

import java.util.Hashtable;
import java.util.List;

import net.sf.hibernate.HibernateException;

import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.runtime.HibernateSession;
import com.hd123.rumba.runtime.Manager;

public class CollateMgr extends Manager implements ICollateMgr {

  /** key = Collate.label, value = Collate */
  private static Hashtable<String, Collate> tableLabelName = new Hashtable();
  /**
   * key = Collate.name, value = hashtable <br>
   * value.key = CollateItem.label, value.value = CollateItem
   */
  private static Hashtable<String, Hashtable<String, CollateItem>> fieldLabelName = new Hashtable();
  private boolean initialized = false;

  public CollateMgr() {
    super();
  }

  private void checkIn() throws BusinessException {
    if (initialized)
      return;
    // 初始化tableLabelName, fieldLabelName
    try {
      try {
        List collates = HibernateSession.getSession().find("from Collate");
        for (int i = 0; i < collates.size(); ++i) {
          Collate collate = (Collate) collates.get(i);
          tableLabelName.put(collate.getLabel(), collate);
          Hashtable fields = (Hashtable) fieldLabelName.get(collate.getName());
          if (fields == null) {
            fields = new Hashtable();
            fieldLabelName.put(collate.getName(), fields);
          }
          for (int j = 0; j < collate.getItems().size(); ++j) {
            CollateItem collateItem = (CollateItem) collate.getItems().get(j);
            fields.put(collateItem.getLabel(), collateItem);
          }
        }
      } finally {
        HibernateSession.closeSession();
      }
      initialized = true;
    } catch (HibernateException e) {
      throw new BusinessException(e);
    }
  }

  public String getTableName(String tableLabel) throws BusinessException {
    checkIn();
    Collate collate = null;
    collate = (Collate) tableLabelName.get(tableLabel);
    if (collate == null)
      return tableLabel;
    else
      return collate.getName();
  }

  public String getFieldName(String tableName, String fieldLabel) throws BusinessException {
    checkIn();
    CollateItem collateItem = null;
    Hashtable fields = (Hashtable) fieldLabelName.get(tableName);
    if (fields != null)
      collateItem = (CollateItem) fields.get(fieldLabel);
    if (collateItem == null)
      return fieldLabel;
    return collateItem.getName();
  }
}
